Commit Graph

79 Commits

  • feat(coding-agent): complete steer()/followUp() migration
    - Update settings-manager with steeringMode/followUpMode (migrates old queueMode)
    - Update sdk.ts to use new mode options
    - Update settings-selector UI to show both modes
    - Add Alt+Enter keybind for follow-up messages
    - Update RPC API: steer/follow_up commands, set_steering_mode/set_follow_up_mode
    - Update rpc-client with new methods
    - Delete dead code: queue-mode-selector.ts
    - Update tests for new API
    - Update mom/context.ts stubs
    - Update web-ui example
  • feat(coding-agent): update AgentSession for steer()/followUp() API
    - Rename queueMessage to steer(), add followUp()
    - Split _pendingMessages into _steeringMessages and _followUpMessages
    - Update sendHookMessage to accept deliverAs option
    - Rename hasQueuedMessages to hasPendingMessages
    - Rename queuedMessageCount to pendingMessageCount
    - Update clearQueue() return type to { steering, followUp }
    - Update UI to show steering vs follow-up messages differently
    
    WIP: settings-manager, sdk, interactive-mode, rpc-mode still need updates
  • Add guard against concurrent prompt() calls
    Agent.prompt() and Agent.continue() now throw if called while already
    streaming, preventing race conditions and corrupted state. Use
    queueMessage() to queue messages during streaming, or await the
    previous call.
    
    AgentSession.prompt() has the same guard with a message directing
    users to queueMessage().
    
    Ref #403
  • Fix edit tool failing on files with UTF-8 BOM
    Strip BOM before matching (LLM won't include invisible BOM in oldText),
    restore on write.
    
    Based on #394 by @prathamdby
  • fix(coding-agent): prevent full re-renders during write tool streaming
    Move line count from header to footer to avoid changing the first line
    during streaming, which was triggering full screen re-renders in the
    TUI's differential rendering logic.
  • Split HookContext and HookCommandContext to prevent deadlocks
    HookContext (all events):
    - isIdle() - read-only state check
    - hasQueuedMessages() - read-only state check
    - abort() - fire-and-forget, does not wait
    
    HookCommandContext (slash commands only):
    - waitForIdle() - waits for agent to finish
    - newSession(options?) - create new session
    - branch(entryId) - branch from entry
    - navigateTree(targetId, options?) - navigate session tree
    
    Session control methods moved from HookAPI (pi.*) to HookCommandContext (ctx.*)
    because they can deadlock when called from event handlers that run inside
    the agent loop (tool_call, tool_result, context events).
  • Add session management and agent state methods to hooks API
    HookAPI additions:
    - pi.newSession(options?) - create new session with optional setup callback
    - pi.branch(entryId) - branch from a specific entry
    - pi.navigateTree(targetId, options?) - navigate the session tree
    
    HookContext additions:
    - ctx.isIdle() - check if agent is streaming
    - ctx.waitForIdle() - wait for agent to finish
    - ctx.abort() - abort current operation
    - ctx.hasQueuedMessages() - check for queued user messages
    
    These enable hooks to programmatically manage sessions (handoff, templates)
    and check agent state before showing interactive UI.
    
    Fixes #388
  • Consolidate session events: remove session_before_new/session_new, add reason field to switch events
    - Remove session_before_new and session_new hook events
    - Add reason: 'new' | 'resume' to session_before_switch and session_switch events
    - Remove 'new' reason from custom tool onSession (use 'switch' for both /new and /resume)
    - Rename reset() to newSession(options?) in AgentSession
    - Add NewSessionOptions with optional parentSession for lineage tracking
    - Rename branchedFrom to parentSession in SessionHeader
    - Rename RPC reset command to new_session with optional parentSession
    - Update example hooks to use new event structure
    - Update documentation and changelog
    
    Based on discussion in #293
  • Add ctx.ui.theme getter for styling status text with theme colors
    - Add theme property to HookUIContext interface
    - Implement in interactive, RPC, and no-op contexts
    - Add status-line.ts example hook
    - Document styling with theme colors in hooks.md
  • Hooks can render custom status (#385)
    * Add ctx.ui.setStatus(key, text) API for hooks to display status in footer
    
    - Add setStatus to HookUIContext interface
    - Implement in interactive mode (FooterComponent)
    - Implement in RPC mode (fire-and-forget)
    - Add no-op implementations for headless contexts
    - Multiple statuses displayed on single line, sorted by key
    - Supports ANSI styling (hooks handle their own colors)
    
    * Remove setStatus from changelog for now
    
    * Fix hook status API to follow TUI rules
    
    - Sanitize status text: replace newlines, tabs, carriage returns with spaces
    - Truncate combined status line to terminal width using truncateToWidth
    - Update JSDoc to document sanitization and truncation behavior
    - Remove unused createHookUIContext method
    - Add missing setStatus to test mock
    
    * Add setStatus to changelog
    
    * Use dim ellipsis for hook status truncation for consistency with footer style
    
    ---------
    
    Co-authored-by: Mario Zechner <badlogicgames@gmail.com>
  • Coalesce sequential status messages
    Rapidly changing settings no longer spams the chat log with multiple status lines.
    
    fixes #365
  • Add setEditorText/getEditorText to hook UI context, improve custom() API
    - Add setEditorText() and getEditorText() to HookUIContext for prompt generator pattern
    - custom() now accepts async factories for fire-and-forget work
    - Add CancellableLoader component to tui package
    - Add BorderedLoader component for hooks with cancel UI
    - Export HookAPI, HookContext, HookFactory from main package
    - Update all examples to import from packages instead of relative paths
    - Update hooks.md and custom-tools.md documentation
    
    fixes #350
  • Change branch() to use entryId instead of entryIndex
    - AgentSession.branch(entryId: string) now takes entry ID
    - SessionBeforeBranchEvent.entryId replaces entryIndex
    - getUserMessagesForBranching() returns entryId
    - Update RPC types and client
    - Update UserMessageSelectorComponent
    - Update hook examples and tests
    - Update docs (hooks.md, sdk.md)
  • Rework custom tools API with CustomToolContext
    - CustomAgentTool renamed to CustomTool
    - ToolAPI renamed to CustomToolAPI
    - ToolContext renamed to CustomToolContext
    - ToolSessionEvent renamed to CustomToolSessionEvent
    - Added CustomToolContext parameter to execute() and onSession()
    - CustomToolFactory now returns CustomTool<any, any> for type compatibility
    - dispose() replaced with onSession({ reason: 'shutdown' })
    - Added wrapCustomTool() to convert CustomTool to AgentTool
    - Session exposes setToolUIContext() instead of leaking internals
    - Fix ToolExecutionComponent to sync with toolOutputExpanded state
    - Update all custom tool examples for new API
  • refactor(coding-agent): fix compaction for branched sessions, consolidate hook context types
    Compaction API:
    - prepareCompaction() now takes (pathEntries, settings) only
    - CompactionPreparation restructured: removed cutPoint/messagesToKeep/boundaryStart, added turnPrefixMessages/isSplitTurn/previousSummary/fileOps/settings
    - compact() now takes (preparation, model, apiKey, customInstructions?, signal?)
    - Fixed token overflow by using getPath() instead of getEntries()
    
    Hook types:
    - HookEventContext renamed to HookContext
    - HookCommandContext removed, RegisteredCommand.handler takes (args, ctx)
    - HookContext now includes model field
    - SessionBeforeCompactEvent: removed previousCompactions/model, added branchEntries
    - SessionBeforeTreeEvent: removed model (use ctx.model)
    - HookRunner.initialize() added for modes to set up callbacks
  • Refactor: move compaction code to src/core/compaction/
    - Move compaction.ts to src/core/compaction/compaction.ts
    - Extract branch summarization to src/core/compaction/branch-summarization.ts
    - Add index.ts to re-export all compaction utilities
    - Update all imports across the codebase
  • Add tree navigation tests and shared test utilities
    - Add test/utilities.ts with shared helpers (API_KEY, userMsg, assistantMsg, createTestSession)
    - Add agent-session-tree-navigation.test.ts with e2e tests for tree navigation
    - Add getChildren() method to SessionManager
    - Add summaryEntry to navigateTree return type
    - Update existing tests to use shared utilities
  • Fix branch summarization abort handling and tree navigation
    - Check response.stopReason instead of catching errors for abort detection
    - Return result object from _generateBranchSummary instead of throwing
    - Fix summary attachment: attach to navigation target position, not old branch
    - Support root-level summaries (parentId=null) in branchWithSummary
    - Remove setTimeout hack for re-showing tree selector on abort
  • refactor(hooks): split session events into individual typed events
    Major changes:
    - Replace monolithic SessionEvent with reason discriminator with individual
      event types: session_start, session_before_switch, session_switch,
      session_before_new, session_new, session_before_branch, session_branch,
      session_before_compact, session_compact, session_shutdown
    - Each event has dedicated result type (SessionBeforeSwitchResult, etc.)
    - HookHandler type now allows bare return statements (void in return type)
    - HookAPI.on() has proper overloads for each event with correct typing
    
    Additional fixes:
    - AgentSession now always subscribes to agent in constructor (was only
      subscribing when external subscribe() called, breaking internal handlers)
    - Standardize on undefined over null throughout codebase
    - HookUIContext methods return undefined instead of null
    - SessionManager methods return undefined instead of null
    - Simplify hook exports to 'export type * from types.js'
    - Add detailed JSDoc for skipConversationRestore vs cancel
    - Fix createBranchedSession to rebuild index in persist mode
    - newSession() now returns the session file path
    
    Updated all example hooks, tests, and emission sites to use new event types.
  • Use exhaustive switch on message.role throughout coding-agent
    - addMessageToChat: exhaustive switch for all AgentMessage roles
    - renderSessionContext: delegates to addMessageToChat, special handling for assistant tool calls and tool results
    - export-html formatMessage: exhaustive switch for all AgentMessage roles
    - Removed isHookMessage, isBashExecutionMessage type guards in favor of role checks
    - Fixed imports and removed unused getLatestCompactionEntry
  • WIP: Major cleanup - move Attachment to consumers, simplify agent API
    - Removed Attachment from agent package (now in web-ui/coding-agent)
    - Agent.prompt now takes (text, images?: ImageContent[])
    - Removed transports from web-ui (duplicate of agent package)
    - Updated coding-agent to use local message types
    - Updated mom package for new agent API
    
    Remaining: Fix AgentInterface.ts to compose UserMessageWithAttachments
  • WIP: Refactor agent package - not compiling
    - Renamed AppMessage to AgentMessage throughout
    - New agent-loop.ts with AgentLoopContext, AgentLoopConfig
    - Removed transport abstraction, Agent now takes streamFn directly
    - Extracted streamProxy to proxy.ts utility
    - Removed agent-loop from pi-ai (now in agent package)
    - Updated consumers (coding-agent, mom) for AgentMessage rename
    - Tests updated but some consumers still need migration
    
    Known issues:
    - AgentTool, AgentToolResult not exported from pi-ai
    - Attachment not exported from pi-agent-core
    - ProviderTransport removed but still referenced
    - messageTransformer -> convertToLlm migration incomplete
    - CustomMessages declaration merging not working properly
  • Add ui.custom() for custom hook components with keyboard focus
    - Add custom() to HookUIContext: returns { close, requestRender }
    - Component receives keyboard input via handleInput()
    - CustomMessageComponent default rendering now limits to 5 lines when collapsed
    - Add snake.ts example hook with /snake command
  • Refactor: shared exec utility, rename CustomMessageRenderer to HookMessageRenderer
    - Extract execCommand to src/core/exec.ts, shared by hooks and custom-tools
    - Rename CustomMessageRenderer -> HookMessageRenderer
    - Rename registerCustomMessageRenderer -> registerMessageRenderer
    - Renderer now receives HookMessage instead of CustomMessageEntry
    - CustomMessageComponent now has setExpanded() and responds to Ctrl+E toggle
    - Re-export ExecOptions/ExecResult from exec.ts for backward compatibility
  • Fix tests for sessionManager/modelRegistry on context
    - compaction-hooks-example.test.ts: get sessionManager/modelRegistry from ctx
    - compaction-hooks.test.ts:
      - Pass sessionManager/modelRegistry to HookRunner constructor
      - Remove setSessionFile call
      - Update tests to use session.sessionManager instead of event.sessionManager
  • Hook API: replace send() with sendMessage(), add appendEntry() and registerCommand()
    Breaking changes to Hook API:
    - pi.send(text, attachments?) replaced with pi.sendMessage(message, triggerTurn?)
      - Creates CustomMessageEntry instead of user messages
      - Properly handles queuing during streaming via agent loop
      - Supports optional turn triggering when idle
    - New pi.appendEntry(customType, data?) for hook state persistence
    - New pi.registerCommand(name, options) for custom slash commands
    - Handler types renamed: SendHandler -> SendMessageHandler, new AppendEntryHandler
    
    Implementation:
    - AgentSession.sendHookMessage() handles all three cases:
      - Streaming: queues message with _hookData marker, agent loop processes it
      - Not streaming + triggerTurn: appends to state/session, calls agent.continue()
      - Not streaming + no trigger: appends to state/session only
    - message_end handler routes based on _hookData presence to correct persistence
    - HookRunner gains getRegisteredCommands() and getCommand() methods
    
    New types: HookMessage<T>, RegisteredCommand, CommandContext
  • Add CustomMessageEntry rendering infrastructure
    - Add renderCustomMessage to HookAPI for registering custom renderers
    - Add CustomMessageRenderer type and CustomMessageRenderOptions
    - Store customMessageRenderers in LoadedHook
    - Add getCustomMessageRenderer(customType) to HookRunner
    - SessionContext.entries now aligned with messages (same length, corresponding indices)
    
    TUI can now correlate messages with their source entries to identify
    custom_message entries and use hook-provided renderers.
  • Refactor SessionEventBase to pass sessionManager and modelRegistry
    Breaking changes to hook types:
    - SessionEventBase now passes sessionManager and modelRegistry directly
    - before_compact: passes preparation, previousCompactions (newest first)
    - before_switch: has targetSessionFile; switch: has previousSessionFile
    - Removed resolveApiKey (use modelRegistry.getApiKey())
    - getSessionFile() returns string | undefined for in-memory sessions
    
    Updated:
    - All session event emissions in agent-session.ts
    - Hook examples (custom-compaction.ts, auto-commit-on-exit.ts, confirm-destructive.ts)
    - Tests (compaction-hooks.test.ts, compaction-hooks-example.test.ts)
    - export-html.ts guards for in-memory sessions
  • Add label support for session entries
    - Add LabelEntry type with targetId and label (string | undefined)
    - Add labelsById map built on load via linear scan
    - Add getLabel(id) and appendLabelChange(targetId, label) methods
    - Add label field to SessionTreeNode, populated by getTree()
    - Update createBranchedSession to preserve labels for entries on path
    - Labels are ignored by buildSessionContext (not sent to LLM)
    - Add comprehensive tests for label functionality
  • Session tree: simplify types, add branching API, comprehensive tests
    Types:
    - SessionEntryBase with type field, extended by all entry types
    - CustomEntry for hooks (type: 'custom', customType, data)
    - Remove XXXContent types and TreeNode (redundant)
    
    API:
    - Rename saveXXX to appendXXX with JSDoc explaining tree semantics
    - Rename branchInPlace to branch() with better docs
    - Add createBranchedSession(leafId) replacing index-based version
    - Add getTree() returning SessionTreeNode[] for tree traversal
    - Add appendCustomEntry(customType, data) for hooks
    
    Tests:
    - tree-traversal.test.ts: 28 tests covering append, getPath, getTree,
      branch, branchWithSummary, createBranchedSession
    - save-entry.test.ts: custom entry integration
    
    Docs:
    - Class-level JSDoc explaining append-only tree model
    - Method docs explaining leaf advancement and branching
    - CHANGELOG.md entry for all changes
  • Refactor session manager: migration chain, validation, tests
    - Add migrateV1ToV2/migrateToCurrentVersion for extensible migrations
    - createSummaryMessage now takes timestamp from entry
    - loadEntriesFromFile validates session header
    - findMostRecentSession only returns valid session files (reads first 512 bytes)
    - Remove ConversationEntry alias
    - Fix mom context.ts TreeNode type
    
    Tests:
    - migration.test.ts: v1 migration, idempotency
    - build-context.test.ts: 14 tests covering trivial, compaction, branches
    - file-operations.test.ts: loadEntriesFromFile, findMostRecentSession
  • Fix SessionEntry type to exclude SessionHeader
    - SessionEntry now only contains conversation entries (messages, compaction, etc.)
    - SessionHeader is separate, not part of SessionEntry
    - FileEntry = SessionHeader | SessionEntry (for file storage)
    - getEntries() filters out header, returns SessionEntry[]
    - Added getHeader() for accessing session metadata
    - Updated compaction and tests to not expect header in entries
    - Updated mom package to use FileEntry for internal storage
  • Fix API key priority and compaction bugs
    - getEnvApiKey: ANTHROPIC_OAUTH_TOKEN now takes precedence over ANTHROPIC_API_KEY
    - findCutPoint: Stop scan-backwards loop at session header (was decrementing past it causing null preparation)
    - generateSummary/generateTurnPrefixSummary: Throw on stopReason=error instead of returning empty string
    - Test files: Fix API key priority order, use keepRecentTokens=1 for small test conversations
  • Session tree structure with id/parentId linking
    - Add TreeNode base type with id, parentId, timestamp
    - Add *Content types for clean input/output separation
    - Entry types are now TreeNode & *Content intersections
    - SessionManager assigns id/parentId on save, tracks leafId
    - Add migrateSessionEntries() for v1 to v2 conversion
    - Migration runs on load, rewrites file
    - buildSessionContext() uses tree traversal from leaf
    - Compaction returns CompactionResult (content only)
    - Hooks return compaction content, not full entries
    - Add firstKeptEntryId to before_compact hook event
    - Update mom package for tree fields
    - Better error messages for compaction failures
  • Fix edit tool failing on Windows due to CRLF line endings
    Normalize line endings to LF before matching, restore original style on write.
    Files with CRLF now match when LLMs send LF-only oldText.
    
    Fixes #355
  • Refactor OAuth/API key handling: AuthStorage and ModelRegistry
    - Add AuthStorage class for credential storage (auth.json)
    - Add ModelRegistry class for model management with API key resolution
    - Add discoverAuthStorage() and discoverModels() discovery functions
    - Add migration from legacy oauth.json and settings.json apiKeys to auth.json
    - Remove configureOAuthStorage, defaultGetApiKey, findModel, discoverAvailableModels
    - Remove apiKeys from Settings type and SettingsManager methods
    - Rename getOAuthPath to getAuthPath
    - Update SDK, examples, docs, tests, and mom package
    
    Fixes #296
  • Add before_compact hook event (closes #281) (#285)
    * Add before_compact hook event (closes #281)
    
    * Add compact hook event and documentation
    
    - Add compact event that fires after compaction completes
    - Update hooks.md with lifecycle diagram, field docs, and example
    - Add CHANGELOG entry
    - Add comprehensive test coverage (10 tests) for before_compact and compact events
    - Tests cover: event emission, cancellation, custom entry, error handling, multiple hooks
  • Add before/after session events with cancellation support
    - Merge branch event into session with before_branch/branch reasons
    - Add before_switch, before_clear, shutdown reasons
    - before_* events can be cancelled with { cancel: true }
    - Update RPC commands to return cancelled status
    - Add shutdown event on process exit
    - New example hooks: confirm-destructive, dirty-repo-guard, auto-commit-on-exit
    
    fixes #278
  • Add project-specific settings and SettingsManager factories
    - SettingsManager now loads .pi/settings.json from cwd (project settings)
    - Project settings merge with global settings (deep merge for objects)
    - Setters only modify global settings, project settings are read-only
    - Add static factories: SettingsManager.create(cwd?, agentDir?), SettingsManager.inMemory(settings?)
    - Add applyOverrides() for programmatic overrides
    - Replace 'settings' option with 'settingsManager' in CreateAgentSessionOptions
    - Update examples to use new pattern
    
    Incorporates PR #276 approach
  • Fix session-manager simplification issues
    - Remove unused inspector import from session-manager.ts
    - Remove dead code in _persist()
    - Update tests for simplified SessionHeader
    - Update mom context.ts: remove unused AgentState import, fix startSession(), rename isEnabled to isPersisted
  • Refactor SessionManager to use static factory methods
    - Add factory methods: create(cwd), open(path), continueRecent(cwd), inMemory()
    - Add static list(cwd) for session listing
    - Make constructor private, pass cwd explicitly
    - Update SDK to take sessionManager instead of sessionFile options
    - Update main.ts to create SessionManager based on CLI flags
    - Update SessionSelectorComponent to take sessions[] instead of SessionManager
    - Update tests to use factory methods
  • feat(coding-agent): add --skills CLI flag for filtering skills
    Adds glob pattern support for skill filtering:
    - --skills <patterns> CLI flag (comma-separated glob patterns)
    - includeSkills setting in settings.json
    - ignoredSkills now supports glob patterns
    - ignoredSkills takes precedence over includeSkills and --skills
    
    Closes #268