Commit Graph

73 Commits

Author SHA1 Message Date
can1357 ef415e863b feat(coding-agent): refactored settings system with new singleton API and unified schema
- Replaced SettingsManager class with new Settings singleton providing synchronous get/set API and background persistence.
- Introduced settings-schema.ts as single source of truth for all configuration definitions with 100+ settings organized into logical groups.
- Migrated from method-based settings access (getTheme(), setTheme()) to path-based access using dot notation (settings.get('theme'), settings.set('theme', value)).
- Removed 2035-line settings-manager.ts file and replaced with modular settings.ts (693 lines) and settings-schema.ts (836 lines) for improved maintainability.
- Unified settings schema into single source of truth eliminating duplicate definitions across settings-defs.ts and settings-manager.ts.
2026-02-01 08:08:58 +01:00
can1357 cc90ed37f8 refactor: extracted padding logic into reusable utility function with optimized buffer allocation
- Extracted manual space padding logic into a reusable `padding()` utility function across all UI components and utilities.
- Optimized padding operations by introducing a pre-allocated 512-space buffer in the `padding()` function to reduce repeated string allocations.
- Updated all imports across 30 files to use the new `padding()` function from pi-tui instead of inline `' '.repeat()` calls.
- Renamed local variables from `padding` to `pad`, `padSize`, `indent`, or `linePad` to avoid naming conflicts with the imported `padding()` function.
- Exported the `padding()` utility function from the tui package index for public use.
2026-01-31 13:36:54 +01:00
can1357 779ca4872b style(deps): migrated from Prettier to Biome and updated formatting rules
- Removed Prettier configuration files (.prettierignore and .prettierrc) and migrated formatting to Biome.
- Updated Biome configuration from version 2.3.11 to 2.3.12 and changed arrowParentheses rule from 'always' to 'asNeeded'.
- Pinned @biomejs/biome dependency to exact version 2.3.12 in package.json and bun.lock.
- Applied consistent arrow function formatting across 489 files by removing unnecessary parentheses around single parameters.
- Removed blank lines after comment blocks and reorganized imports for consistency across the codebase.
2026-01-24 04:20:19 +01:00
can1357 e22d123009 refactor(fs): migrated remaining sync file operations to async
- Converted readdirSync, readFileSync, and statSync to async readdir, readFile, stat across skills and agent discovery.
- Made scanDirectoryForSkills async and refactored custom directory scanning to use Promise.all for concurrent processing.
- Updated agent discovery to use fs/promises for async file reading and refactored helper patterns.
- Added AgentParsingError exception class for better error handling during agent parsing.
- Added filesystem error type guards (isEnoent, isEacces, isPerm, etc.) to pi-utils for safe error checking.
- Added color manipulation utilities to pi-utils for accessibility features.
- Added color-blind mode setting to settings manager.
- Migrated plugins, settings, and config modules from sync to async file operations.
- Updated error handling to use new pi-utils type guards for type-safe checking.
2026-01-24 03:18:03 +01:00
can1357 b9c9330ea1 feat: enhanced usage providers to extract account identifiers from headers
- Enhanced usage providers to extract account identifiers from response headers.
- Fixed GitHub Copilot usage provider token handling and account identifier resolution.
- Added usage report deduplication and provider sorting features.
- Added isolated task execution with git worktree management.
2026-01-21 23:52:03 +01:00
can1357 21af96d890 fix: added Cursor OAuth provider and fixed authentication flow race conditions
- Added Cursor OAuth provider support to CLI authentication flow.
- Fixed race conditions in OAuth callback handling and session picker cleanup.
- Improved JWT token parsing and error handling across OAuth providers.
- Replaced Bun.sleep() with abortable sleep for proper cancellation support.
- Enhanced process execution with concurrent stream reading and better timeout handling.
- Added cache cleanup mechanism for auth storage with 5-minute intervals.
2026-01-20 19:50:50 +01:00
can1357 ac151519c1 feat: port upstream changes from pi-mono (72047c05..55769e75)
AI provider fixes:
- Fixed Claude tool prefix matching and Gemini 3 unsigned tool handling
- Added Bedrock thinking budget guardrails and tool id sanitization
- Added tool argument coercion and Codex response retry logic

TUI improvements:
- Improved Kitty key handling and editor behavior (scrolling, padding, kill ring)

Coding agent changes:
- Added extension input interception, compaction helpers, and UI updates
- Added session forking prompt for cross-project sessions
- Added APPEND_SYSTEM discovery, piped stdin print mode, and key hint exports

Docs:
- Updated pi-mono sync point
2026-01-18 17:52:58 +01:00
can1357 827841d19f fix(ai/providers): fixed schema sanitization and standardized priority format to string labels
- Fixed Google provider schema sanitization to collapse anyOf/oneOf with const values into enum arrays.
- Fixed const-to-enum conversion to infer type from const value when type is not specified.
- Changed review finding priority format from numeric (0-3) to string labels (P0-P3).
- Replaced Type.Union with Type.Literal patterns with StringEnum helper across tool schemas.
- Added const modifier to StringEnum generic type parameter for improved TypeScript type inference.
- Consolidated priority metadata into single PRIORITY_INFO record with exported getPriorityInfo function.
2026-01-12 01:02:47 +01:00
can1357 e6d33e0a48 feat(coding-agent): converted capability loading and discovery providers to async APIs with caching fs layer
- Converted SettingsManager.create(), loadSettings(), discoverSkills(), loadSlashCommands(), buildSystemPrompt(), loadSkills(), loadProjectContextFiles(), and getShellConfig() from synchronous to asynchronous APIs.
- Changed capability provider load() method from supporting both sync and async to async-only by removing loadSync().
- Removed fs property from LoadContext interface in capability types.
- Added new fs.ts module with caching layer for filesystem operations using readFile, readDirEntries, readDir, walkUp, and cache management functions.
- Refactored all discovery providers (builtin, claude, cline, codex, cursor, gemini, github, mcp-json, ssh, vscode, windsurf) to use async file operations with Promise.all for parallel loading.
2026-01-11 04:26:43 +01:00
can1357 86ef2bd34b chore: bump version to 3.34.0 2026-01-09 12:17:04 +01:00
can1357 5a63120dd3 feat(ai): add @oh-my-pi/pi-ai package with tool name prefixing
- Port pi-ai from upstream with Bun-first approach (source files, no dist)
- Add cli_ prefix to tool names in OAuth mode to avoid collisions
- Improve beta header handling with proper deduplication
- Convert codex-instructions.md to Bun text embed
- Strip .js extensions from all imports
2026-01-09 12:10:03 +01:00
can1357 02cae69bb5 feat: added session storage abstraction and configurable bash interceptor rules
- Added in-memory session storage abstraction with SessionStorage interface and MemorySessionStorage implementation.
- Added configurable bash interceptor rules with pattern-based command interception settings.
- Added AbortSignal support to 80+ web scrapers for request cancellation.
- Changed task tool to require explicit task `id` field and single `agent` parameter at top level.
- Removed `submit_review` tool - reviewers now use `complete` tool with structured output.
- Replaced Date.now() and crypto.randomUUID() with nanoid() for unique ID generation throughout codebase.
2026-01-07 23:17:09 +01:00
can1357 753be5d87f feat: introduced Worker-based subagent execution with BUILTIN_TOOLS registry
- Added ToolSession interface and Bun Worker-based subagent execution replacing subprocess spawning.
- Added BUILTIN_TOOLS registry and createTools factory function replacing individual tool exports.
- Added toolNames parameter for filtering which built-in tools to include in agent sessions.
- Removed deprecated tool exports (codingTools, readOnlyTools, createCodingTools, createReadOnlyTools).
- Removed subagent custom tool example and question custom tool example.
2026-01-07 03:03:34 +01:00
can1357 5919b0df94 refactor: switched to upstream @mariozechner/pi-ai and removed unused packages
- Replaced local @oh-my-pi/pi-ai with upstream @mariozechner/pi-ai@0.37.4
- Added sessionId support to agent for provider caching (OpenAI Codex)
- Deleted packages/ai (now using upstream)
- Deleted packages/mom (unused)
- Deleted packages/web-ui (unused)
2026-01-06 22:25:24 +00:00
can1357 15fbe228b3 feat(monorepo): merged codex providers and extensions 2026-01-05 15:37:44 +01:00
can1357 7f1d071843 feat(coding-agent): added streaming NDJSON session persistence with crash-safe writes
Rewrote SessionManager to use streaming NDJSON writes with proper backpressure
handling instead of synchronous file appends. Key changes:

- SessionManager.open() and continueRecent() are now async for proper init
- Session writes use atomic rename pattern with fsync for crash safety
- Added flush() method for explicit control over pending write completion
- Large content blocks (>500KB) are truncated before writing to prevent OOM
- Images are replaced with placeholder thumbnails during persistence
2026-01-05 04:20:44 +01:00
can1357 790a5370bb feat: renamed binary from pi to omp with config migration support
- Renamed CLI binary and package from 'pi' to 'omp' across all platforms and installers.
- Changed environment variable prefix from PI_* to OMP_* with automatic migration support.
- Changed configuration directory from ~/.pi/ to ~/.omp/ with multi-path fallback discovery.
- Added getConfigDirPaths(), findConfigFile(), and readConfigFile() functions for config resolution across .omp, .pi, and .claude directories.
2026-01-03 15:54:45 +01:00
can1357 50ab6b8b1b style: removed .js extension from imports and added node: prefix to builtins 2026-01-03 05:12:25 +01:00
can1357 c70303ade9 feat(coding-agent): added structured code review with hidden tools and explicit opt-in
- Added hidden property for custom tools to exclude them from default tool list unless explicitly requested.
- Added explicitTools option to createAgentSession for enabling hidden tools by name.
- Added example review tools (report_finding, submit_review) with structured findings accumulation and verdict rendering.
- Added /review command for interactive code review with branch comparison, uncommitted changes, and commit review modes.
- Updated bundled reviewer agent to use structured review tools with priority-based findings (P0-P3) and formal verdict submission.
2026-01-03 05:08:20 +01:00
can1357 2be354322d chore: renamed package scope to @oh-my-pi for consistent branding
- Renamed npm package scope from @mariozechner to @oh-my-pi across all packages for consistent branding.
- Removed packages/pods directory and all related pod management functionality.
- Updated import paths and module declarations throughout codebase to reflect new package names.
- Reformatted code with consistent trailing comma removal and ternary operator alignment.
2026-01-02 18:08:23 +01:00
can1357 560c9670a8 feat: added MCP support and plugin system for external tool integration
- Added MCP (Model Context Protocol) support with stdio and HTTP transports for external tool integration.
- Implemented plugin system with install, enable, configure, and doctor commands for extensibility.
- Added 22 Exa MCP tools for web search, LinkedIn, company research, and websets operations.
- Introduced LSP tool with rust-analyzer support for code intelligence (diagnostics, hover, references, code actions).
- Added task tool for delegating work to specialized subagents with parallel execution support.
- Implemented web_search and web_fetch tools with Anthropic and Perplexity provider support.
2026-01-02 17:54:42 +01:00
can1357 b85d3f6aa4 merge(pi/main): integrate upstream changes through v0.31.1
Merged 53 commits from pi/main including:
- Export HTML rewrite with tree sidebar and /share command
- Hooks API enhancements (custom status, editor, session management)
- Edit diff preview before tool execution
- TUI fixes (Unicode format chars, OSC 8 hyperlinks, emoji optimization)
- Gemini CLI rate limit retry with server-provided delay
- Various bug fixes and documentation updates

Resolved conflicts by preserving Bun migration (spawn→Bun.spawn,
fs→Bun.file) while accepting upstream's new features and APIs.
2026-01-02 14:34:27 +01:00
Mario Zechner cc397427b9 Update docs for ctx.ui.editor() and handoff example
- Added ctx.ui.editor() to hooks.md and custom-tools.md
- Added ctx.ui.editor() to CHANGELOG.md
- Added handoff.ts to examples/hooks/README.md
2026-01-02 01:26:21 +01:00
Mario Zechner d8b94822c8 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.
2026-01-02 01:11:06 +01:00
Mario Zechner fbada4e653 Use serializeConversation in handoff hook
Properly handles all message types including tool calls, thinking,
and tool results instead of manual text extraction.
2026-01-02 00:45:03 +01:00
Mario Zechner 2314cb0930 Add handoff example hook
Transfers context to a new focused session instead of compacting.
User provides a goal, hook generates a prompt with relevant context,
creates a new session with parent tracking, and loads the prompt
as a draft in the editor for review.

Inspired by Amp's handoff feature.
2026-01-02 00:42:11 +01:00
Mario Zechner f107f980c9 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
2026-01-01 23:31:26 +01:00
Mario Zechner 7720f3512b 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
2026-01-01 21:58:01 +01:00
Mario Zechner b849a76a07 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
2026-01-01 00:04:56 +01:00
Mario Zechner c583a31192 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)
2025-12-31 13:47:34 +01:00
Mario Zechner 399daef215 Update custom-compaction example to use serializeConversation
Also fix docs to show convertToLlm is needed first.
2025-12-31 13:24:23 +01:00
Mario Zechner f9caeab90f Reorder execute params: (toolCallId, params, onUpdate, ctx, signal?)
Optional signal now at the end for cleaner API
2025-12-31 12:14:28 +01:00
Mario Zechner ea3d42907f 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
2025-12-31 12:05:24 +01:00
Mario Zechner fa931ceed1 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
2025-12-31 02:24:24 +01:00
Mario Zechner 6632efe323 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.
2025-12-30 22:42:22 +01:00
Mario Zechner ac5ab3d98d Remove allowDuringStreaming flag - commands always run immediately
Hook commands now always execute immediately, even during streaming.
If a command needs to interact with the LLM, it uses pi.sendMessage()
which handles queueing automatically.

This simplifies the API and eliminates the issue of queued slash
commands being sent to the LLM instead of executing.
2025-12-30 22:42:22 +01:00
Mario Zechner a509b2fdf2 Rename immediate -> allowDuringStreaming for hook commands 2025-12-30 22:42:22 +01:00
Mario Zechner e8947026a8 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
2025-12-30 22:42:20 +01:00
Mario Zechner 5a4a85a927 Fix snake border alignment using visibleWidth for proper ANSI length calculation 2025-12-30 22:42:20 +01:00
Mario Zechner 7a6b70c99c Snake: add full border frame and pause/resume with session persistence
- Full box border around title, game area, and instructions
- ESC pauses and saves state to session via pi.appendEntry()
- Resume shows 'PAUSED - press any key to continue'
- Q quits and clears saved state
- High score persists across games
2025-12-30 22:42:20 +01:00
Mario Zechner c65ca451fb Fix snake velocity: render cells as 2 chars wide for square aspect
Terminal cells are ~2:1 aspect ratio, so movement appeared faster
vertically. Now each game cell is 2 characters wide.
2025-12-30 22:42:19 +01:00
Mario Zechner ab95f049ab Improve snake game visuals
- Rounded box corners (╭╮╰╯)
- Better characters: ● head, ○ body, ◆ food, · empty
- Colored title with emoji
- Dimmed borders and help text
- Bold highlights for score and controls
2025-12-30 22:42:19 +01:00
Mario Zechner fd044441ff Add immediate flag to hook commands for non-queued execution
Commands with immediate: true run right away even during streaming.
Used for UI-only commands like /snake that don't interact with LLM.
2025-12-30 22:42:19 +01:00
Mario Zechner 2bc6459827 Fix snake.ts: use key helpers from pi-tui for ESC and arrow keys 2025-12-30 22:42:19 +01:00
Mario Zechner 0a55cd295a 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
2025-12-30 22:42:19 +01:00
Mario Zechner d1ecb8aee3 Move exec to HookAPI, sessionManager/modelRegistry to HookEventContext
Breaking changes:
- HookEventContext now has sessionManager and modelRegistry (moved from SessionEventBase)
- HookAPI now has exec() method (moved from HookEventContext/HookCommandContext)
- HookRunner constructor takes sessionManager and modelRegistry as required params
- Session events no longer include sessionManager/modelRegistry fields

Hook code migration:
- event.sessionManager -> ctx.sessionManager
- event.modelRegistry -> ctx.modelRegistry
- ctx.exec() -> pi.exec()

Updated:
- src/core/hooks/types.ts - type changes
- src/core/hooks/runner.ts - constructor, createContext
- src/core/hooks/loader.ts - add exec to HookAPI
- src/core/sdk.ts - pass sessionManager/modelRegistry to HookRunner
- src/core/agent-session.ts - remove sessionManager/modelRegistry from events
- src/modes/* - remove setSessionFile calls, update events
- examples/hooks/* - update to new API
2025-12-30 22:42:19 +01:00
Mario Zechner e568ef6bb0 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
2025-12-30 22:42:18 +01:00
Mario Zechner f6e784bc9a 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
2025-12-30 22:42:18 +01:00
Mario Zechner baa1e10747 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
2025-12-30 22:42:17 +01:00
Mario Zechner ea7e8704aa 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
2025-12-30 22:42:17 +01:00