Commit Graph

442 Commits

  • 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
  • Skills standard compliance
    Implement Agent Skills standard (https://agentskills.io/specification):
    - Validate name (must match parent dir, lowercase, max 64 chars)
    - Validate description (required, max 1024 chars)
    - Warn on unknown frontmatter fields
    - Warn on name collisions (keep first)
    - Change prompt format to XML structure
    - Remove {baseDir} placeholder (use relative paths)
    - Add tests and update documentation
    
    fixes #231
  • Add --version/-v flag to CLI (#170)
    - Parse --version and -v flags in args.ts
    - Handle version flag early in main.ts (print and exit)
    - Add flag to help text
    - Add comprehensive test coverage for CLI arg parsing
    
    Co-authored-by: cc-vps <crcatala+vps@gmail.com>
  • Fix branch selector for single message and --no-session mode
    - Allow branch selector to open with single user message (changed <= 1 to === 0 check)
    - Support in-memory branching for --no-session mode (no files created)
    - Add isEnabled() getter to SessionManager
    - Update sessionFile getter to return null when sessions disabled
    - Update SessionSwitchEvent types to allow null session files
    - Add branching tests for single message and --no-session scenarios
    
    fixes #163
  • Simplify compaction: remove proactive abort, use Agent.continue() for retry
    - Add agentLoopContinue() to pi-ai for resuming from existing context
    - Add Agent.continue() method and transport.continue() interface
    - Simplify AgentSession compaction to two cases: overflow (auto-retry) and threshold (no retry)
    - Remove proactive mid-turn compaction abort
    - Merge turn prefix summary into main summary
    - Add isCompacting property to AgentSession and RPC state
    - Block input during compaction in interactive mode
    - Show compaction count on session resume
    - Rename RPC.md to rpc.md for consistency
    
    Related to #128
  • feat(coding-agent): implement new compaction system with overflow recovery
    Phase 1: Updated compaction.ts
    - findCutPoint now returns CutPointResult with isSplitTurn and turnStartIndex
    - Can cut at user, assistant, or bashExecution messages (never tool results)
    - Added turnPrefixSummary support for split turns (parallel summarization)
    - estimateTokens helper for context size estimation
    
    Phase 2: Updated session-manager.ts
    - CompactionEntry now has optional turnPrefixSummary field
    - loadSessionFromEntries injects both summaries when turn was split
    
    Phase 3: Updated agent-session.ts
    - Overflow detection via isContextOverflow after agent_end
    - Proactive compaction check on turn_end before next LLM call
    - _abortingForCompaction flag to skip saving aborted messages
    - Auto-retry after overflow recovery or proactive compaction
    - New event fields: reason (overflow/threshold), willRetry
    
    Phase 4: Updated interactive-mode.ts
    - Shows reason in compaction status (Context overflow detected...)
    - Shows retry status after compaction
    
    Tests updated for new CutPointResult return type.
  • Fix agent event ordering: update state before emitting events
    Previously, Agent.emit() was called before state was updated (e.g., appendMessage).
    This meant event handlers saw stale state - when message_end fired,
    agent.state.messages didn't include the message yet.
    
    Now state is updated first, then events are emitted, so handlers see
    consistent state that matches the event.
  • Rewrite RPC mode with typed protocol and client
    - Move RPC files to modes/rpc/ directory
    - Add properly typed RpcCommand and RpcResponse types
    - Expose full AgentSession API via RPC commands:
      - State: get_state
      - Model: set_model, cycle_model, get_available_models
      - Thinking: set_thinking_level, cycle_thinking_level
      - Queue: set_queue_mode
      - Compaction: compact, set_auto_compaction
      - Bash: bash, abort_bash
      - Session: get_session_stats, export_html, switch_session, branch, etc.
    - Add RpcClient class for programmatic access
    - Rewrite tests to use RpcClient instead of raw process spawning
    - All commands support optional correlation ID for request/response matching
  • Add test fixture for auto-compaction testing
    Session at ~98% context usage, triggers auto-compaction with single prompt
  • Add bash mode for executing shell commands
    - Add ! prefix in TUI editor to execute shell commands directly
    - Output streams in real-time and is added to LLM context
    - Supports multiline commands, cancellation (Escape), truncation
    - Preview mode shows last 20 lines, Ctrl+O expands full output
    - Commands persist in session history as bashExecution messages
    - Add bash command to RPC mode via {type:'bash',command:'...'}
    - Add RPC tests for bash command execution and context inclusion
    - Update docs: rpc.md, session.md, README.md, CHANGELOG.md
    
    Closes #112
    
    Co-authored-by: Markus Ylisiurunen <markus.ylisiurunen@gmail.com>
  • Add totalTokens field to Usage type
    - Added totalTokens field to Usage interface in pi-ai
    - Anthropic: computed as input + output + cacheRead + cacheWrite
    - OpenAI/Google: uses native total_tokens/totalTokenCount
    - Fixed openai-completions to compute totalTokens when reasoning tokens present
    - Updated calculateContextTokens() to use totalTokens field
    - Added comprehensive test covering 13 providers
    
    fixes #130
  • fix: TUI crash with Unicode characters in branch selector
    - Use truncateToWidth instead of substring in user-message-selector.ts
    - Fix truncateToWidth to use Intl.Segmenter for proper grapheme handling
    - Add tests for Unicode truncation behavior
  • feat(coding-agent): add auto-compaction to RPC mode, add RPC compaction test
    - RPC mode now auto-compacts when context exceeds threshold (same as TUI)
    - Add RPC test for manual compaction via compact command
    - Auto-compaction emits compaction event with auto: true flag
  • WIP: Context compaction core logic (#92)
    - Add CompactionEntry type with firstKeptEntryIndex
    - Add loadSessionFromEntries() for compaction-aware loading
    - Add compact() function that returns CompactionEntry
    - Add token calculation and cut point detection
    - Add tests with real session fixture and LLM integration
    
    Still TODO: settings, /compact and /autocompact commands, auto-trigger in TUI, /branch rework
  • fix(coding-agent): use describe.skipIf for RPC test with explicit model
    - Use describe.skipIf pattern matching other tests
    - Skip when ANTHROPIC_API_KEY and ANTHROPIC_OAUTH_TOKEN are missing
    - Use explicit --provider anthropic --model claude-sonnet-4-5
  • fix: RPC mode session management not saving sessions
    Since version 0.9.0, RPC mode (--mode rpc) was not saving messages to
    session files. The agent.subscribe() call with session management logic
    was only present in the TUI renderer after it was refactored.
    
    RPC mode now properly saves sessions just like interactive mode.
    
    Added test for RPC mode session management to prevent regression.
    
    Fixes #83
    
    Thanks @kiliman for reporting this issue!
  • feat(coding-agent): add read-only exploration tools (grep, find, ls) and --tools flag
    Add grep, find, and ls tools for safe code exploration without modification risk.
    These tools are available via the new --tools CLI flag.
    
    - grep: Uses ripgrep (auto-downloaded) for fast regex searching. Respects .gitignore,
      supports glob filtering, context lines, and hidden files.
    - find: Uses fd (auto-downloaded) for fast file finding. Respects .gitignore, supports
      glob patterns, and hidden files.
    - ls: Lists directory contents with proper sorting and directory indicators.
    - --tools flag: Specify available tools (e.g., --tools read,grep,find,ls for read-only mode)
    - Dynamic system prompt adapts to selected tools with relevant guidelines
    
    Closes #74
  • Improve edit tool diff display with context-aware rendering
    - Add generateDiffString() function in edit tool to create unified diffs with line numbers and 4 lines of context
    - Store only the formatted diff string in tool result details instead of full file contents
    - Update tool-execution renderer to parse and colorize the diff string
    - Filter out message_update events from session saving to prevent verbose session files
    - Add markdown nested list and table rendering tests
  • Add proper truncation notices and comprehensive tests for read tool
    **Improved output messages:**
    1. File fits within limits: Just outputs content (no notices)
    2. Lines get truncated: Shows "Some lines were truncated to 2000 characters for display"
    3. File doesn't fit limit: Shows "N more lines not shown. Use offset=X to continue reading"
    4. Offset beyond file: Shows "Error: Offset X is beyond end of file (N lines total)"
    5. Both truncations: Combines both notices with ". " separator
    
    **Comprehensive test coverage:**
    - Files within limits (no notices)
    - Large files (line truncation)
    - Long lines (character truncation)
    - Offset parameter
    - Limit parameter
    - Offset + limit together
    - Invalid offset (out of bounds)
    - Combined truncations (both notices)
    
    All 17 tests passing ✓
  • Add image support in tool results across all providers
    Tool results now use content blocks and can include both text and images.
    All providers (Anthropic, Google, OpenAI Completions, OpenAI Responses)
    correctly pass images from tool results to LLMs.
    
    - Update ToolResultMessage type to use content blocks
    - Add placeholder text for image-only tool results in Google/Anthropic
    - OpenAI providers send tool result + follow-up user message with images
    - Fix Anthropic JSON parsing for empty tool arguments
    - Add comprehensive tests for image-only and text+image tool results
    - Update README with tool result content blocks API