Commit Graph

282 Commits

  • Custom tools with session lifecycle, examples for hooks and tools
    - Custom tools: TypeScript modules that extend pi with new tools
      - Custom TUI rendering via renderCall/renderResult
      - User interaction via pi.ui (select, confirm, input, notify)
      - Session lifecycle via onSession callback for state reconstruction
      - Examples: todo.ts, question.ts, hello.ts
    
    - Hook examples: permission-gate, git-checkpoint, protected-paths
    
    - Session lifecycle centralized in AgentSession
      - Works across all modes (interactive, print, RPC)
      - Unified session event for hooks (replaces session_start/session_switch)
    
    - Box component added to pi-tui
    
    - Examples bundled in npm and binary releases
    
    Fixes #190
  • Release v0.22.4
    - Add --list-models CLI flag for listing/finding models with fuzzy search
    
    fixes #203
  • Fix image limits test to use realistic payload sizes
    Previous test used compressed 8k images (0.01MB) which was meaningless.
    Now tests with actual large noise images that don't compress.
    
    Realistic payload limits discovered:
    - Anthropic: 6 x 3MB = ~18MB total (not 32MB as documented)
    - OpenAI: 2 x 15MB = ~30MB total
    - Gemini: 10 x 20MB = ~200MB total (very permissive)
    - Mistral: 4 x 10MB = ~40MB total
    - xAI: 1 x 20MB (strict request size limit)
    - Groq: 5 x 5760px images (5 image + pixel limit)
    - zAI: 2 x 15MB = ~30MB (50MB request limit)
    - OpenRouter: 2 x 5MB = ~10MB total
    
    Also fixed GEMINI_API_KEY env var (was GOOGLE_API_KEY).
    
    Related to #120
  • Add tool result streaming
    - Add AgentToolUpdateCallback type and optional onUpdate callback to AgentTool.execute()
    - Add tool_execution_update event with toolCallId, toolName, args, partialResult
    - Normalize tool_execution_end to always use AgentToolResult (no more string fallback)
    - Bash tool streams truncated rolling buffer output during execution
    - ToolExecutionComponent shows last N lines when collapsed (not first N)
    - Interactive mode handles tool_execution_update events
    - Update RPC docs and ai/agent READMEs
    
    fixes #44
  • GitHub Copilot: auto-enable models, fix gpt-5 API, normalize tool call IDs
    - Auto-enable all models after /login via POST /models/{model}/policy
    - Use openai-responses API for gpt-5/o3/o4 models (not accessible via completions)
    - Normalize tool call IDs when switching between github-copilot models with different APIs
      (fixes #198: openai-responses generates 450+ char IDs with special chars that break other models)
    - Update README with streamlined GitHub Copilot docs
  • Add GitHub Copilot support (#191)
    - OAuth login for GitHub Copilot via /login command
    - Support for github.com and GitHub Enterprise
    - Models sourced from models.dev (Claude, GPT, Gemini, Grok, etc.)
    - Dynamic base URL from token's proxy-ep field
    - Use vscode-chat integration ID for API compatibility
    - Documentation for model enablement at github.com/settings/copilot/features
    
    Co-authored-by: cau1k <cau1k@users.noreply.github.com>
  • feat: initial impl
    - add GitHub Copilot model discovery (env token fallback, headers,
    compat) plus fallback list and quoted provider keys in generated map
    - surface Copilot provider end-to-end (KnownProvider/default, env+OAuth
    token refresh/save, enterprise base URL swap, available only when
    creds/env exist)
    - tweak interactive OAuth UI to render instruction text and prompt
    placeholders
    
    gpt-5.2-high took about 35 minutes. It had a lot of trouble with `npm
    check`  and went off on a "let's adjust every tsconfig" side quest.
    Device code flow works, but the ai/scripts/generate-models.ts impl is
    wrong as models from months ago are missing and only those deprecated
    are accessible in the /models picker.
  • Fix image rendering artifacts and improve show-images selector
    - Image component returns correct number of lines (rows) for TUI accounting
    - Empty lines rendered first, then cursor moves up and image is drawn
    - This clears the space the image occupies before rendering
    - Add spacer before inline images in tool output
    - Create ShowImagesSelectorComponent with borders like other selectors
    - Use showSelector pattern for /show-images command
  • Add /show-images command to toggle inline image display
    - Add terminal.showImages setting to settings-manager.ts
    - Add /show-images slash command (only visible if terminal supports images)
    - ToolExecutionComponent checks both terminal support and user setting
    - Shows text fallback when inline images are disabled
  • coding-agent, mom: add skills API export and mom skills auto-discovery
    coding-agent:
    - Export loadSkillsFromDir, formatSkillsForPrompt, and related types
    - Refactor skills.ts to expose public API
    
    mom:
    - Add skills auto-discovery from workspace/skills and channel/skills
    - Fix skill loading to use host paths (not Docker container paths)
    - Update README and system prompt with SKILL.md format docs
  • coding-agent: change Pi skills to use SKILL.md convention
    Breaking change: Pi skills must now be named SKILL.md inside a directory,
    matching Codex CLI format. Previously any *.md file was treated as a skill.
    
    Migrate by renaming ~/.pi/agent/skills/foo.md to ~/.pi/agent/skills/foo/SKILL.md
  • Add skills system with Claude Code compatibility (#171)
    * Add skills system with Claude Code compatibility
    
    * consolidate skills into single module, merge loaders, add <available_skills> XML tags
    
    * add Codex CLI skills compatibility, skip hidden/symlinks
  • 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>
  • mom: refactor to use AgentSession for context management
    - Export AgentSession, SessionManager, SettingsManager, compaction from coding-agent
    - Create MomSessionManager for channel-based context.jsonl storage
    - Create MomSettingsManager for mom-specific settings
    - Refactor agent.ts to use AgentSession instead of ephemeral Agent
    - Split logging: tool results go to context.jsonl, human messages to log.jsonl
    - Enable auto-compaction and overflow detection from coding-agent
    
    Part of #115
  • Auto-retry on transient provider errors (overloaded, rate limit, 5xx)
    - Add retry logic with exponential backoff (2s, 4s, 8s) in AgentSession
    - Disable Anthropic SDK built-in retries (maxRetries: 0) to allow app-level handling
    - TUI shows retry status with Escape to cancel
    - RPC mode: add set_auto_retry, abort_retry commands and auto_retry_start/end events
    - Configurable via settings.json: retry.enabled, retry.maxRetries, retry.baseDelayMs
    - Exclude context overflow errors from retry (handled by compaction)
    
    fixes #157
  • Fix git branch indicator in subdirectories
    Walk up directory hierarchy to find .git/HEAD instead of only checking cwd.
    
    fixes #156
  • 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
  • feat: add line number display to HTML export for read tool calls
    Implements line number display in HTML exports for read tool calls, matching the TUI format.
    When offset/limit parameters are provided, displays path:startLine-endLine in yellow color.
    
    Fixes #166
  • fixes #161: stop theme watcher and exit cleanly in print mode
    The theme file watcher was keeping the Node.js process alive indefinitely
    even in print mode where hot-reload is unnecessary. This simple fix calls
    stopThemeWatcher() and process.exit(0) after print mode completes.
    
    - Added stopThemeWatcher() call after runPrintMode() completes
    - Added process.exit(0) to ensure clean process termination
    - Imported stopThemeWatcher from theme module
    
    This is a minimal fix that addresses the symptom (process hanging) without
    changing the theme initialization logic.
  • fixes #161: disable theme watcher in print mode
    The theme file watcher was keeping the Node.js process alive indefinitely
    even in print mode where hot-reload is unnecessary. This fix adds an
    enableWatcher parameter to initTheme() and setTheme() functions, and only
    enables watchers in interactive mode.
    
    - Modified initTheme() to accept enableWatcher parameter (default: false)
    - Modified setTheme() to accept enableWatcher parameter (default: false)
    - Updated main.ts to only enable watchers in interactive mode
    - Updated InteractiveMode to enable watchers when changing themes
  • Add Mistral as AI provider
    - Add Mistral to KnownProvider type and model generation
    - Implement Mistral-specific compat handling in openai-completions:
      - requiresToolResultName: tool results need name field
      - requiresAssistantAfterToolResult: synthetic assistant message between tool/user
      - requiresThinkingAsText: thinking blocks as <thinking> text
      - requiresMistralToolIds: tool IDs must be exactly 9 alphanumeric chars
    - Add MISTRAL_API_KEY environment variable support
    - Add Mistral tests across all test files
    - Update documentation (README, CHANGELOG) for both ai and coding-agent packages
    - Remove client IDs from gemini.md, reference upstream source instead
    
    Closes #165
  • Add hooks system with pi.send() for external message injection
    - Hook discovery from ~/.pi/agent/hooks/, .pi/hooks/, --hook flag
    - Events: session_start, session_switch, agent_start/end, turn_start/end, tool_call, tool_result, branch
    - tool_call can block execution, tool_result can modify results
    - pi.send(text, attachments?) to inject messages from external sources
    - UI primitives: ctx.ui.select/confirm/input/notify
    - Context: ctx.exec(), ctx.cwd, ctx.sessionFile, ctx.hasUI
    - Docs shipped with npm package and binary builds
    - System prompt references docs folder
  • feat(coding-agent): implement hooks system
    - Add hooks infrastructure in core/hooks/ (loader, runner, types)
    - HookUIContext interface with mode-specific implementations
    - Interactive mode: TUI-based selector/input/confirm dialogs
    - RPC mode: JSON protocol for hook UI requests/responses
    - Print mode: no-op UI context (hooks run but can't prompt)
    - AgentSession.branch() now async, returns { selectedText, skipped }
    - Settings: hooks[] and hookTimeout configuration
    - Export hook types from package for hook authors
    
    Based on PR #147 proposal, adapted for new architecture.
  • 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 hardcoded truncation limits in tool output display
    - Add maxLines and maxBytes fields to TruncationResult to track actual limits used
    - Update tool-execution.ts to use actual limits from truncation result
    - Add fallbacks to DEFAULT_MAX_* for backward compatibility with old sessions
    - Fix outdated comments that said 30KB when default is 50KB
  • feat(coding-agent): maintain in-memory session entries for --no-session compaction support
    SessionManager now tracks all entries in memory regardless of whether file
    persistence is enabled. This allows compaction to work in --no-session mode
    where no session file is created.
    
    - Added inMemoryEntries array to store session entries
    - All save methods now push to inMemoryEntries
    - loadEntries() returns in-memory entries when file persistence is disabled
    - File persistence only writes when enabled flag is true
    - Session loading (constructor, setSessionFile) populates in-memory entries
  • 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
  • Fix auto-compaction TUI integration and cut point logic
    - Trigger auto-compaction after agent_end instead of during message_end
    - Show CompactionComponent after auto-compaction (same as manual /compact)
    - Fix cut point to include bash executions before kept user message
    - Stop backward scan at compaction, assistant, user, or toolResult boundaries
  • Add auto-compaction events to AgentSession
    - Add AgentSessionEvent type extending AgentEvent with auto_compaction_start/end
    - Emit events when auto-compaction starts and completes
    - TUI shows loader during auto-compaction with escape to cancel
    - Rebuilds chat UI when auto-compaction succeeds